<template>
  <ContentWrap>
    <el-form size="large" class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="扫码信息" prop="code">
        <el-input @input="handleQuery" v-model="queryParams.code" placeholder="请输入扫码信息" clearable
          @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item label="零件编号" prop="code">
        <el-input @input="handleQuery" v-model="queryParams.partNumber" placeholder="请输入" clearable
          @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['business:code-list:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['business:code-list:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['business:code-list:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <el-tabs v-model="activeName" @tab-click="handleClick" type="border-card">
    <el-tab-pane name="first" label="扫码判定">
      <ContentWrap>
        <el-form size="large" class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true"
          label-width="68px">
          <el-alert title="提示:需切换英文输入法扫码!" type="success" style="margin-bottom: 20px;" />
          <el-form-item label="扫码信息" prop="code">
            <el-input type="textarea" v-model="formData.code" placeholder="请扫描二维码/条形码,并将输入法切换为英文" @blur="onBlur"
              clearable @input="onInput" class="!w-540px" />
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }" row-key="id" border
          v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
          @selection-change="handleRowCheckboxChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="扫码信息" align="center" prop="code" width="300" />
          <el-table-column label="零件编号" align="center" prop="partNumber" width="100" />
          <el-table-column label="供应商代码" align="center" prop="supplyCode" width="100" />
          <el-table-column label="零件唯一码" align="center" prop="partUniqueCode" width="180" />
          <el-table-column label="批次信息" align="center" prop="batchInfo" width="120" />
          <el-table-column label="校验结果" align="center" width="120">
            <template #default="{ row }">
              <el-tag :type="row.factoryInfo === '通过' ? 'success' : 'danger'" effect="plain">
                {{ row.factoryInfo }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="operator" width="120" />
          <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
          <el-table-column fixed="right" label="操作" align="center" min-width="120px">
            <template #default="scope">
              <el-button link type="primary" @click="openForm('update', scope.row.id)"
                v-hasPermi="['business:code-list:update']">
                编辑
              </el-button>
              <el-button link type="danger" @click="handleDelete(scope.row.id)"
                v-hasPermi="['business:code-list:delete']">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
          @pagination="getList" />
      </ContentWrap>
    </el-tab-pane>
    <el-tab-pane name="second" label="失败日志">
      <!-- 列表 -->
      <ContentWrap>
        <el-table :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }" row-key="id" border
          v-loading="loadingFail" :data="listFail" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column label="扫码信息" align="center" prop="code" width="300" />
          <el-table-column label="校验结果" align="center" width="120">
            <template #default="{ row }">
              <el-tag :type="row.factoryInfo === '通过' ? 'success' : 'danger'" effect="plain">
                {{ row.factoryInfo }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="失败原因" align="center" prop="remark" />
          <el-table-column label="创建人" align="center" prop="operator" width="120" />
          <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
          <!-- <el-table-column fixed="right" label="操作" align="center" min-width="120px">
            <template #default="scope">
              <el-button link type="primary" @click="openForm('update', scope.row.id)"
                v-hasPermi="['business:code-list:update']">
                编辑
              </el-button>
              <el-button link type="danger" @click="handleDelete(scope.row.id)"
                v-hasPermi="['business:code-list:delete']">
                删除
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>
        <!-- 分页 -->
        <Pagination :total="totalFail" v-model:page="queryParamsFail.pageNo" v-model:limit="queryParamsFail.pageSize"
          @pagination="getFailList" />
      </ContentWrap>
    </el-tab-pane>
  </el-tabs>


  <!-- 表单弹窗：添加/修改 -->
  <CodeListForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CodeListApi, CodeList } from '@/api/business/codelist'
import CodeListForm from './CodeListForm.vue'

/** 编码信息 列表 */
defineOptions({ name: 'CodeList' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const activeName = ref('first')

const loading = ref(true) // 列表的加载中
const list = ref<CodeList[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  partNumber: undefined,
  code: undefined,
  createTime: [],
  factoryInfo: '通过'
})


const loadingFail = ref(true) // 列表的加载中
const listFail = ref<CodeList[]>([]) // 列表的数据
const totalFail = ref(0) // 列表的总页数
const queryParamsFail = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  createTime: [],
  factoryInfo: '未通过'
})

const handleClick = (item, event) => {
  activeName.value = item.paneName
  if (activeName.value == 'second') {
    getFailList()
  }

  if (activeName.value = 'first') {
    getList()
  }

}

const formData = ref({
  id: undefined,
  code: undefined,
  partNumber: undefined,
  supplyCode: undefined,
  partUniqueCode: undefined,
  batchInfo: undefined,
  factoryInfo: undefined,
  remark: undefined
})

// 假设扫码内容固定为 13 位（如 EAN-13 条形码）

// 假设扫码内容固定为 13 位（如 EAN-13 条形码）
const EXPECTED_LENGTH = 31


// 如果不想引入 lodash，可以自己写一个简易 debounce：
const debounce = (func: Function, delay: number) => {
  let timeoutId: NodeJS.Timeout
  return (...args: any[]) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func(...args), delay)
  }
}

// 校验扫码内容
const isValidationRunning = ref(false)

const validateCode = async () => {
  // 防止重复校验
  if (isValidationRunning.value) return false
  isValidationRunning.value = true

  try {
    const value = formData.value.code?.trim() || ''
    if (value && value.length !== EXPECTED_LENGTH) {
      await message.confirm(`扫码信息长度应为 ${EXPECTED_LENGTH} 位，请重新扫描(需切换英文输入法)！`)
      formData.value.remark = `扫码信息长度应为 ${EXPECTED_LENGTH} 位`;
      //记录失败的
      await CodeListApi.createFailCode(formData.value)
      resetForm()
      formData.value.code = ''
      return false
    }
    return true
  } finally {
    isValidationRunning.value = false
  }
}



// 防抖校验（用于输入停止后检查）
const debouncedValidate = debounce(validateCode, 800)

// 输入事件：除了原有逻辑，增加防抖校验
const onInput = () => {
  const value = formData.value.code?.trim() || ''

  // 如果刚好是期望长度，尝试自动提交（保留你原有逻辑）
  if (value.length === EXPECTED_LENGTH) {
    setTimeout(() => {
      if ((formData.value.code?.trim() || '') === value) {
        handleAdd()
      }
    }, 500)
  }

  // 触发防抖校验（长度不对时提示）
  debouncedValidate()
}

// 失去焦点时也校验（确保用户点别处也能提示）
const onBlur = () => {
  validateCode()
}


const isSubmitting = ref(false)

const handleAdd = async () => {
  if (isSubmitting.value) return // 防止重复提交
  isSubmitting.value = true

  try {
    const temp = formData.value.code
    resetForm()
    formData.value.code = temp

    const result = await CodeListApi.checkData(formData.value)
    if (result.flag === false) {
      await message.confirm(result.message)
      formData.value.remark = result.message
      //记录失败的
      await CodeListApi.createFailCode(formData.value)
      resetForm()
      formData.value.code = ''
    } else {
      await submitForm()
    }
  } catch {
    // error
  } finally {
    isSubmitting.value = false
  }
}

const submitForm = async () => {
  // 校验表单
  // 提交请求
  try {
    const data = formData.value as unknown as CodeList
    if (formData.value.id == undefined || formData.value.id == null) {
      await CodeListApi.createCodeList(data)
      message.success(t('common.createSuccess'))
      resetForm()
      getList()
    } else {
      await CodeListApi.updateCodeList(data)
      message.success(t('common.updateSuccess'))
      resetForm()
      getList()
    }
    // 发送操作成功的事件
  } catch (e) {
    resetForm()
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    partNumber: undefined,
    supplyCode: undefined,
    partUniqueCode: undefined,
    batchInfo: undefined,
    factoryInfo: undefined,
    remark: undefined
  }
}

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CodeListApi.getCodeListPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 查询列表 */
const getFailList = async () => {
  loading.value = true
  try {
    const data = await CodeListApi.getCodeListPage(queryParamsFail)
    listFail.value = data.list
    totalFail.value = data.total
  } finally {
    loadingFail.value = false
  }
}


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}



/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CodeListApi.deleteCodeList(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除编码信息 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await CodeListApi.deleteCodeListList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: CodeList[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CodeListApi.exportCodeList(queryParams)
    download.excel(data, '编码信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
